package com.iyundao.io.controller;

import com.iyundao.io.tools.ImageUtils;
import com.iyundao.io.tools.ResponseData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping(value = "/upload")
public class ImageUploadController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    public ResponseData ActivityImageUpload(MultipartFile file, Integer activityid, Integer partymemberid) {
        if (file.isEmpty()) {
            return new ResponseData(0,"上传文件失败，请选择文件");
        }

        //获取图片名
        String fileName = String.valueOf(System.currentTimeMillis())+".jpg";

        //图片路径
        File dest = new File(uploadFolder +"images/"+ fileName);

        //水印图片路径
        File file2 = new File(uploadFolder + "images/logo1.png");

        if(!dest.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            dest.getParentFile().mkdirs();
            try {
                //创建文件
                dest.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(!file2.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            file2.getParentFile().mkdirs();
            try {
                //创建文件
                file2.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            //图片上传
            file.transferTo(dest);
            //将原图替换为缩略图
            Boolean aBoolean = ImageUtils.createThumbnail(dest, dest, 500, 500);
            if (aBoolean) {
                //缩略图加水印
                Boolean b = ImageUtils.makeWatermark(dest, file2, 10, 10, 0.5F);
                if (b) {
                   return new ResponseData(200,uploadFolder +"images/"+ fileName);
                } else {
                    return new ResponseData(0,"添加水印失败");
                }

            } else {
                return new ResponseData(0,"添加缩略图失败");
            }
        } catch (IOException e) {
            return new ResponseData(0,e.getMessage());
        }

    }

}
